package com.cheng.spider.extract.novel;

import com.cheng.spider.constant.DefaultConstant;
import com.cheng.spider.constant.MimeType;
import com.cheng.spider.extract.ExtractRule;
import com.cheng.spider.extract.HtmlDataResolver;
import com.cheng.spider.extract.Result;
import com.cheng.spider.extract.SaveRule;
import org.jsoup.nodes.Document;

public abstract class NovelExtractor extends HtmlDataResolver {

    protected SaveRule initSaveRule() {
        return new SaveRule() {
            @Override
            public void save(Result result, MimeType mimeType) {
                Paragraph paragraph = (Paragraph) result.get("paragraph");
                if (!NovelWriter.inited()) {
                    NovelWriter.init(getSavePath() + getNovelFileName());
                }
                NovelWriter.write(paragraph.toString());
            }
        };
    }

    protected ExtractRule initExtractorRule() {
        return new ExtractRule() {
            @Override
            public Result extract(Document document) {
                Result result = new Result();
                String title = extractTitle(document);
                String content = extractContent(document);
                result.put("paragraph", new Paragraph(title, content));
                return result;
            }
        };
    }

    protected abstract String extractContent(Document document);

    protected abstract String extractTitle(Document document);

    protected abstract String getNovelFileName();

    protected String getSavePath() {
        return DefaultConstant.CLASSPATH;
    }

}
